import axios, { CancelTokenSource } from 'axios';
import { useCallback, useEffect, useState } from 'react';

export const useAPDrawer = <T extends {}>() => {
  const [visible, setVisible] = useState(false);
  const [record, setRecord] = useState<T | null>(null);

  const handleAddClick = () => {
    setVisible(true);
  };

  const handleEditClick = (record: T) => {
    setRecord(record);
    setVisible(true);
  };

  const handleClose = () => {
    setVisible(false);
    setRecord(null);
  };
  return {
    visible,
    record,
    handleAddClick,
    handleEditClick,
    handleClose,
    setRecord,
  };
};

export const useLoading = () => {
  const [isLoading, setLoading] = useState(false);

  const load = useCallback(async <T extends Promise<any>>(fn: T) => {
    // settimeout 能让最新的请求在 上一个请求finally,catch后执行
    setTimeout(() => {
      setLoading(true);
    });

    try {
      return fn.finally(() => {
        setLoading(false);
      });
    } catch (e) {
      setLoading(false);
    }
  }, []);

  return [isLoading, load] as [boolean, any];
};

export const useCancelApi = <T = any>(api: Function) => {
  const [source, setSource] = useState<CancelTokenSource>();

  const search = useCallback(
    <U>(param: U, header: any = {}): Promise<T> => {
      const CancelToken = axios.CancelToken;
      const source = CancelToken.source();
      setSource(source);
      return api(param, header, source.token);
    },
    [api],
  );

  const getBy = useCallback(
    (param: string, data: any = {}, header: any = {}): Promise<T> => {
      const CancelToken = axios.CancelToken;
      const source = CancelToken.source();
      setSource(source);
      return api(param)(data, header, source.token);
    },
    [api],
  );

  useEffect(() => {
    return () => {
      source?.cancel('请求中断');
    };
  }, [source]);

  return { search, getBy };
};
